import 'package:flutter/material.dart';
import 'gt_tabs.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'gt_under_line_tab_indicator.dart';

/// @Title   公共的下指示器的tabbar
///   指示器宽度为文字的60%，指示器计算宽度和位置计算不包括文字后面的括号内容
/// @Author: bryce
/// @CreateDate: 2023年10月11日15:09:30
class GTUnderlineTabBar extends StatelessWidget {
  final List<String> tabTitles;
  final TabController? controller;
  final EdgeInsetsGeometry? padding;

  // 新增tab切换拦截，如果返回true代表拦截，false允许切换
  final Future<bool> Function(TabController mController, int newIndex)? onInterceptSwitch;

  // 新增拦截点击tab时的切换（对于使用controller控制的和手势滚动TabBarView的切换不拦截）
  final Future<bool> Function(TabController mController, int newIndex)? onInterceptTapSwitch;

  const GTUnderlineTabBar({super.key, required this.tabTitles, this.controller, this.padding, this.onInterceptSwitch,this.onInterceptTapSwitch});

  @override
  Widget build(BuildContext context) {
    EdgeInsets labPadding = GTEdgeInsetsOnly(right: 12);
    TextStyle labelStyle = gtTextStyleW600(fontSize: 16);
    // 小括号style
    TextStyle bracketsStyle = gtTextStyleW500(fontSize: 14);

    return GTTabBar(
      dividerColor: Colors.transparent,
      controller: controller,
      tabs: tabs(bracketsStyle),
      isScrollable: true,
      indicatorColor: GTColorsV3.uikitText1V3.color,
      labelStyle: labelStyle,
      unselectedLabelStyle: gtTextStyleW500(fontSize: 16),
      labelColor: GTColorsV3.uikitText1V3.color,
      unselectedLabelColor: GTColorsV3.uikitText3V3.color,
      labelPadding: labPadding,
      padding: padding,
      onInterceptSwitch: onInterceptSwitch,
      onInterceptTapSwitch: onInterceptTapSwitch,
      indicator: GTUnderlineTabIndicator(
          context: context,
          tabTitles: tabTitles,
          labelPadding: labPadding,
          labelStyle: labelStyle,
          bracketsStyle: bracketsStyle,
          borderSide: BorderSide(width: 3, color: GTColorsV3.uikitText1V3.color)),
    );
  }

  List<Widget> tabs(TextStyle bracketsStyle) {
    return tabTitles.map((e) {
      String currentTitle = e.trim();
      // 获取末尾小括号
      String? bracketsStr = TextUtils.getEndBrackets(currentTitle);
      if (TextUtils.isNotEmpty(bracketsStr)) {
        currentTitle = currentTitle.replaceAll(bracketsStr!, '')..trim();
        return GTTab(
            height: 28,
            alignment: Alignment.topCenter,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(currentTitle),
                const SizedBox(width: 2),
                Text(
                  bracketsStr,
                  style: bracketsStyle,
                )
              ],
            ));
      }
      return GTTab(height: 28, alignment: Alignment.topCenter, child: Text(currentTitle));
    }).toList();
  }
}
